/*
 * Copyright (C) 2013 TinhVan Outsourcing.
 */
package com.media.themovieworld.util.network.httptask;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import android.content.Context;
import android.util.Log;

import com.media.themovieworld.util.network.handler.JsonPaserExceptions;
import com.media.themovieworld.util.network.util.HttpUtil;
import com.media.themovieworld.util.network.util.JsonUtil;

public abstract class MobiNetworkJsonTask<Param, Result> extends MobiNetworkTask<Param, Void, Result> {
    private Class<Result> mType;

    /**
     * @param pContext
     * @param pShowLoading
     */
    public MobiNetworkJsonTask(Context pContext, boolean pShowLoading) {
        super(pContext, pShowLoading);
        this.mType = this.getType();
    }

    public MobiNetworkJsonTask(Context pContext) {
        super(pContext, false);
        this.mType = this.getType();
    }

    // get parameter type from generic class
    // in class return type is result type
    final int indexResultType = 1;

    private Class<Result> getType() {
        @SuppressWarnings("unchecked")
        Class<Result> classType =
                (Class<Result>) ((ParameterizedType) getClass().getGenericSuperclass())
                        .getActualTypeArguments()[indexResultType];
        return classType;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.smartebook.android.mobibook.networkhandler.networktask.MobiNetworkTask#processInBackground
     * (Params[])
     */
    @Override
    public Result processInBackground(Param... pParams) throws IOException {
        final String json = HttpUtil.getStringResponseByGetMethod((String) pParams[0]);
        Log.i("MobiNetworkJsonTask", " Json :" + json);
        Result result = null;
        try {
            result = JsonUtil.fromString(json, mType);
            onDoAfterPaser(result);
        } catch (JsonPaserExceptions e) {
            e.printStackTrace();
            onJsonPaserException(e,mContext.get(),pParams);
        }
        return result;
    }

    protected void onJsonPaserException(Exception exception, Context pContext, Param... param) {

    }
    protected void onDoAfterPaser(Result result) {
        
    }
}
